package com.myc.gateway.filter;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/***
 *
 * 登录拦截器。解析token拿到loginid
 */
@Component
@Slf4j
public class LoginFilter implements GlobalFilter {
    @Override
    @SneakyThrows
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //拿到请求
        ServerHttpRequest request = exchange.getRequest();
        //拿到请求中可以获取各属性的总体东西
        ServerHttpRequest.Builder mutate = request.mutate();
        //定义黑白名单，拿到url判断是否拦截
        String url = request.getURI().getPath();
        log.info("LoginFilter.filter.url:{}",url);
        if (url.equals("/user/doLogin")){
            //放行
            chain.filter(exchange);
        }
        //获取登录token的唯一性loginid
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        String loginId = (String) tokenInfo.getLoginId();
        //将loginid放入到请求header中
        mutate.header("loginId",loginId);
        //将request重新构建一下并放行
        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }
}
